package leetcode;

import util.NodeQ0138.Node;

import java.util.HashMap;

/**
 * @Project : algorithm-learning-java
 * @Package : leetcode
 * @Author : Ruoyu Wang
 * @User : Momenta
 * @DateTime : 2024/1/18 15:13
 */
public class Q0138 {
    public Node copyRandomList(Node head) {
        Node h = new Node(-1);
        HashMap<Node, Node> map = new HashMap<>();
        map.put(null, null);
        Node newList = h;
        Node oldList = head;

        while (oldList != null) {
            Node s = new Node(oldList.val);
            newList.next = s;
            map.put(oldList, s);
            oldList = oldList.next;
            newList = newList.next;
        }

        newList = h.next;
        oldList = head;
        while (oldList != null) {
            newList.random = map.get(oldList.random);
            oldList = oldList.next;
            newList = newList.next;
        }

        return h.next;
    }
}
